package com.youxue.teachin.user.login.usercase;

import java.util.Locale;

import com.library.rest.ApiServiceManager;
import com.library.rest.rxjava.RxResultHelper;
import com.library.rest.rxjava.RxSchedulersHelper;
import com.library.rest.vo.ResponseModel;
import com.youxue.teachin.common.vo.ToKenVO;
import com.youxue.teachin.user.repository.IUserRepository;
import com.youxue.teachin.user.userSystem.UserSystem;
import rx.Observable;
import rx.functions.Func1;

/**
 * 在此写用途
 *
 * @author: zhiwei
 * @date: 2017-10-05 16:41
 * @version: 9.1.0
 */
public class LoginUserCase {
    IUserRepository mIUserRepository;
    public LoginUserCase() {
        Class<IUserRepository> clazz = IUserRepository.class;
        mIUserRepository = ApiServiceManager.getOrCreateApiService(clazz);
    }

    public Observable<ToKenVO> login(String phone, String password) {
        return mIUserRepository.login(phone, password)
            .compose(RxSchedulersHelper.<ResponseModel<ToKenVO>>io_main())
            .compose(RxResultHelper.<ToKenVO>handleResult())
            .map(new Func1<ToKenVO, ToKenVO>() {
                @Override
                public ToKenVO call(ToKenVO toKenVO) {
                    UserSystem.getInstance().setToken(toKenVO.token, toKenVO.tokenId);
                    return toKenVO;
                }
            })
            ;
    }

    public Observable<ToKenVO> loginThreed(String code, String state) {

        return mIUserRepository.loginTheed(code, state, Locale.getDefault().getLanguage(), Locale.getDefault().getCountry())
            .compose(RxSchedulersHelper.<ResponseModel<ToKenVO>>io_main())
            .compose(RxResultHelper.<ToKenVO>handleResult())
            .map(new Func1<ToKenVO, ToKenVO>() {
                @Override
                public ToKenVO call(ToKenVO toKenVO) {
                    UserSystem.getInstance().setToken(toKenVO.token, toKenVO.tokenId);
                    return toKenVO;
                }
            })
            ;
    }


    public Observable<Void> loginOut() {
        return mIUserRepository.loginOut()
            .map(new Func1<ResponseModel<Void>, ResponseModel<Void>>() {
                @Override
                public ResponseModel<Void> call(ResponseModel<Void> voidResponseModel) {
                    UserSystem.getInstance().loginOut();
                    return voidResponseModel;
                }
            })
            .compose(RxSchedulersHelper.<ResponseModel<Void>>io_main())
            .compose(RxResultHelper.<Void>handleResult())
            ;
    }


}
